package com.upup.train_management.controller;

import com.upup.train_management.entity.Train;
import com.upup.train_management.service.TrainService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/trains")
public class TrainController {

    private final TrainService trainService;

    @Autowired
    public TrainController(TrainService trainService) {
        this.trainService = trainService;
    }

    @GetMapping
    public ResponseEntity<List<Train>> getAllTrains() {
        return ResponseEntity.ok(trainService.getAllTrains());
    }

    @GetMapping("/{id}")
    public ResponseEntity<Train> getTrainById(@PathVariable Long id) {
        Train train = trainService.getTrainById(id);
        if (train != null) {
            return ResponseEntity.ok(train);
        }
        return ResponseEntity.notFound().build();
    }

    @GetMapping("/number/{trainNumber}")
    public ResponseEntity<Train> getTrainByNumber(@PathVariable String trainNumber) {
        Train train = trainService.getTrainByNumber(trainNumber);
        if (train != null) {
            return ResponseEntity.ok(train);
        }
        return ResponseEntity.notFound().build();
    }

    @PostMapping
    public ResponseEntity<Train> createTrain(@RequestBody Train train) {
        return ResponseEntity.ok(trainService.saveTrain(train));
    }

    @PutMapping("/{id}")
    public ResponseEntity<Train> updateTrain(@PathVariable Long id, @RequestBody Train train) {
        Train existingTrain = trainService.getTrainById(id);
        if (existingTrain == null) {
            return ResponseEntity.notFound().build();
        }
        train.setId(id);
        return ResponseEntity.ok(trainService.saveTrain(train));
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteTrain(@PathVariable Long id) {
        Train existingTrain = trainService.getTrainById(id);
        if (existingTrain == null) {
            return ResponseEntity.notFound().build();
        }
        trainService.deleteTrain(id);
        return ResponseEntity.noContent().build();
    }
}